package com.yunfei.yikao.web.controlller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.yunfei.yikao.web.dao.ZhangyunfeiYikaoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Email;

/**
 * @Author: yunfei
 * @Date: 12:08
 */
@Controller
public class EmailControl {
    @Autowired
     private ZhangyunfeiYikaoMapper yikaoMapper;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    DefaultKaptcha kaptcha;

    @RequestMapping("/sendemail")
    @ResponseBody
    public String send(HttpSession session,@RequestParam("email") String email) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("yunfei66641@163.com");
            helper.setTo(email);
            helper.setSubject("主题： 验证码");
            String code = kaptcha.createText();
            session.setAttribute("emailcode", code);
            message.setText("<h1>" + code + "</h1>", "utf-8", "html");
            mailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "发送邮件";
//        SimpleMailMessage message = new SimpleMailMessage();
//        message.setFrom("yunfei66641@163.com");
//        message.setTo("yunfei66641@163.com");
//        message.setSubject("主题： 验证码");
//        String code = kaptcha.createText();
//        session.setAttribute("emailCode", code);
//        message.setText(code);
//        mailSender.send(message);
//        return "发送邮件";
    }

    @RequestMapping(path = "/checkemailcode")
//       判断验证码及邮箱有验证码是否正确，不正确返回注册页面
    public String check(@RequestParam("code") String emailcode, @SessionAttribute("emailCode") String sessionEmailCode,
                        @RequestParam("captcha") String captcha, @SessionAttribute("captcha") String sessionCaptcha,
                        HttpSession session) {
        if (emailcode.equals(sessionEmailCode)) {
            session.removeAttribute("emailCode");
            if (captcha.equals(sessionCaptcha)) {
                return "index";
            } else {
                return "login";
            }

        } else {
            return "login";
        }
    }


}
